package com.paomi.client.activity.search;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.paomi.client.MyApplication;
import com.paomi.client.R;
import com.paomi.client.activity.classify.adapter.ClassifyListAdapter;
import com.paomi.client.activity.classify.model.SearchGetBeaan;
import com.paomi.client.activity.newsDetail.model.NewsListJson;
import com.paomi.client.activity.search.adapter.SearchListAdapter;
import com.paomi.client.activity.search.adapter.SearchTicketAdapter;
import com.paomi.client.base.BaseMvpActivity;
import com.paomi.client.fragment.first.model.TicketJson;
import com.paomi.client.net.Constants;
import com.paomi.client.refresh.AdapterWrapper;
import com.paomi.client.refresh.SwipeToLoadHelper;
import com.paomi.client.utils.UIUtils;
import com.paomi.client.widget.RxToast;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SearchActivity extends BaseMvpActivity<SearchMvpView, SearchPresenter> implements SearchMvpView ,SwipeToLoadHelper.LoadMoreListener {

    @BindView(R.id.tv_search_icon)
    TextView tvSearchIcon;
    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.tv_search_clear)
    TextView tvSearchClear;
    @BindView(R.id.search_list)
    RecyclerView searchList;
    @BindView(R.id.ll_none)
    LinearLayout llNone;
    private List<TicketJson> ticketJsonList=new ArrayList<>();//请求的演出列表
    private SearchListAdapter historyAdapter;
//    private SearchTicketAdapter ticketAdapter;
    private ClassifyListAdapter classifyListAdapter;
    private List<String> historyData=new ArrayList<>();//保存的历史信息
    private List<String> getList=new ArrayList<>();
    private int pageNum=1;
    //上拉加载更多
//    private AdapterWrapper mAdapterWrapper;
//    private SwipeToLoadHelper mLoadMoreHelper;
    private String searchContent="";
    private List<SearchGetBeaan> classifyList=new ArrayList<>();//搜索列表的数据
    private List<NewsListJson> listJsons=new ArrayList<>();//资讯数据信息

    @NonNull
    @Override
    public SearchPresenter createPresenter() {
        return new SearchPresenter();
    }

    @Override
    protected String setTitle() {
        return getResources().getString(R.string.search_text);
    }

    @Override
    protected void showBack(TextView button_goback) {
        button_goback.setVisibility(View.VISIBLE);
        button_goback.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
        button_goback.setTextColor(getResources().getColor(R.color.main_color));
        button_goback.setText(getResources().getString(R.string.back_normal) + getResources().getString(R.string.back));
        button_goback.setTypeface(iconfont);
    }

    @NonNull
    @Override
    protected int getLayoutId() {
        return R.layout.activity_search;
    }

    @Override
    protected void initEvent() {
        tvSearchIcon.setTypeface(iconfont);
        tvSearchClear.setTypeface(iconfont);
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if ((actionId == 6) || (actionId == 2) || ((event != null) && (event.getAction() == 0) && (event.getKeyCode() == 66))) {
                    if (etSearch.getText().toString() == null || etSearch.getText().toString().length() < 1) {
                        RxToast.info(getResources().getString(R.string.search_null));
                        return true;
                    }
                    classifyList.clear();
                    searchContent=etSearch.getText().toString();
                    commitHistory(etSearch.getText().toString());
                    return true;
                }
                return false;
            }
        });
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if(count>0){
                    tvSearchClear.setVisibility(View.VISIBLE);
                }else{
                    tvSearchClear.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        searchList.setLayoutManager(UIUtils.getRecyclerViewManager(false,this));
        historyAdapter=new SearchListAdapter(this,iconfont);
//        ticketAdapter=new SearchTicketAdapter(this);
        classifyListAdapter=new ClassifyListAdapter(this,iconfont);
//        mAdapterWrapper = new AdapterWrapper(ticketAdapter);
//        mLoadMoreHelper = new SwipeToLoadHelper(searchList, mAdapterWrapper);
//        mLoadMoreHelper.setLoadMoreListener(this);
        getHistory();
        if(ticketJsonList.size()>0){
            llNone.setVisibility(View.GONE);
        }else{
            llNone.setVisibility(View.VISIBLE);
        }
        if(historyData.size()>0){
            getList.clear();
            getList.add(getResources().getString(R.string.search_lately));
            llNone.setVisibility(View.GONE);
            searchList.setAdapter(historyAdapter);
            historyAdapter.setData(getList,historyData);
            historyAdapter.OnItemClick(new SearchListAdapter.OnItemClick() {
                @Override
                public void setOnItemClick(View view, int pos) {
                    searchContent=historyData.get(pos);
                    etSearch.setText(searchContent);
                    pageNum=1;
                    //请求接口
                    getPresenter().setTicketJsonList(pageNum,searchContent);
                    getPresenter().setInfoData(pageNum,searchContent,"0");
                }

                @Override
                public void setOnItemDelete(View view, int pos) {//删除搜索记录
                    historyData.clear();
                    clearHistory();
                    historyAdapter.notifyDataSetChanged();
                    if(etSearch.getText().toString().trim().equals("")){
                        llNone.setVisibility(View.VISIBLE);
                    }
                }
            });
        }else{
            llNone.setVisibility(View.VISIBLE);
        }
    }

    @OnClick(R.id.tv_search_clear)
    public void onViewClicked() {
        etSearch.setText("");
        tvSearchClear.setVisibility(View.GONE);
    }
    public void commitHistory(String key) {
        //收起软键盘
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(etSearch.getWindowToken(), 0);

        etSearch.setText(key);
        pageNum=1;
        //请求接口
        getPresenter().setTicketJsonList(pageNum,key);
        getPresenter().setInfoData(pageNum,key,"0");
        SharedPreferences sp = getSharedPreferences("setting", MODE_PRIVATE);
        String historyString = sp.getString("actionHistory", "");

        historyString = historyString.replace(key + ",", "");

        historyString = historyString.replace("," + key, "");

        if (historyString.equals(key)) historyString = "";

        if (historyString.length() == 0) historyString = key;

        else historyString = key + "," + historyString;
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("actionHistory", historyString);
        editor.commit();
    }

    public void getHistory() {
        historyData.clear();
        // 获取历史记录
        SharedPreferences sp = MyApplication.getAppContext().getSharedPreferences("setting", 0);
        String historyString = sp.getString("actionHistory", "");
        if (historyString.length() == 0) {
            return;
        }
        String strs[] = historyString.split(",");
        for (int i = 0; i < strs.length; i++) {
            historyData.add(strs[i]);
        }
    }
    public void clearHistory(){
        SharedPreferences sp = getSharedPreferences("setting", MODE_PRIVATE);
        String historyString = "";
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("actionHistory", historyString);
        editor.commit();
    }

    /**
     *演出列表
     * @param jsonList
     */
    @Override
    public void getTicketList(List<TicketJson> jsonList) {
        if(jsonList.size()>0){
            ticketJsonList.clear();
            ticketJsonList.addAll(jsonList);
            llNone.setVisibility(View.GONE);
//            searchList.setAdapter(ticketAdapter);
//            ticketAdapter.setData(jsonList);
            searchList.setAdapter(classifyListAdapter);
            SearchGetBeaan searchGetBeaan=new SearchGetBeaan();
            searchGetBeaan.setName(getResources().getString(R.string.classify_show));
            classifyList.add(searchGetBeaan);
            classifyListAdapter.setData(classifyList,ticketJsonList,listJsons);
            classifyListAdapter.notifyDataSetChanged();
//            searchList.setAdapter(mAdapterWrapper);
//            mLoadMoreHelper.setLoadMoreFinish();
//            mAdapterWrapper.notifyDataSetChanged();
        }else{
            llNone.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 资讯列表
     * @param result
     */
    @Override
    public void getInfoData(List<NewsListJson> result) {
        if(result.size()>0){
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    llNone.setVisibility(View.GONE);
                    SearchGetBeaan searchGetBeaan=new SearchGetBeaan();
                    searchGetBeaan.setName(getResources().getString(R.string.classify_news));
                    classifyList.add(searchGetBeaan);
                    listJsons.clear();
                    listJsons.addAll(result);
                    classifyListAdapter.setData(classifyList,ticketJsonList,listJsons);
                    classifyListAdapter.notifyDataSetChanged();
                }
            }, 1000);
        }
    }

    @Override
    public void onLoad() {
        if(ticketJsonList.size()%Constants.PAGE_SIZE ==0){//刷新请求
            pageNum++;
            //请求接口
            getPresenter().setTicketJsonList(pageNum,searchContent);
        }else{//没有更多数据
            //移除FooterView
//            mAdapterWrapper.setLoadItemState(false);
        }
    }
}
